package com.lyc.controller.user;

import com.lyc.DTO.UserDTO;
import com.lyc.pojo.Result;
import com.lyc.pojo.User;
import com.lyc.service.UserService;
import com.lyc.utils.JwtUtil;
import com.lyc.utils.Md5Util;
import com.lyc.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.constraints.Pattern;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController// 表示该类是一个控制器
@Validated //  开启参数校验
@CrossOrigin // 添加这一行允许跨域
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 注入redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 用户注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{2,16}$") String username,
                           @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{5,16}$") String password){
        //查询用户名是否已存在
        User u =userService.findByUserName(username);
        if(u == null){
            //没有占用
            //注册
            userService.register(username,password);
            return Result.success();
        }else{
            return Result.error("用户名已占用");
        }
    }

    // 用户登录
    @PostMapping("/login")
    public Result login(String username,String  password){
        //查询用户名
        User u =userService.findByUserName(username);
        if(u == null){
            return Result.error("用户不存在");
        }
        //验证密码
        if(Md5Util.getMD5String(password).equals(u.getPasswordHash())){
            //登录成功，将用户id和名字封装成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            //生成token
            String token = JwtUtil.genToken(claims);
            //将token存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            System.out.println("Token 已存入 Redis: " + token);

            return Result.success(token);

        }
        return Result.error("密码错误");
    }
    //获取用户信息
    @GetMapping("/userinfo")
    public Result<User> Userinfo(){
        //从ThreadLocal中获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        //获取用户username
        String username = (String) map.get("username");
        //查询用户信息
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    // 修改用户信息
    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserDTO  userDTO){
        userService.updateUserInfo(userDTO);
        return Result.success();
    }

    // 修改密码
    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token){
        //获取密码
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        String rePassword = params.get("rePassword");
        //判断是否为空
        if(oldPassword == null || newPassword == null || rePassword == null){
            return Result.error("密码不能为空");
        }

        //获取原密码
        Map<String, Object> map = ThreadLocalUtil.get();
        //获取用名，根据用名查询密码
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        String oldPasswordHash = user.getPasswordHash();
        //验证原密码
        if(!Md5Util.getMD5String(oldPassword).equals(oldPasswordHash)){
            return Result.error("原密码错误");
        }
        if(!newPassword.equals(rePassword)){
            return Result.error("两次密码不一致");
        }
        //修改密码
        userService.updatePassword(newPassword);
        //删除Redis中的token
        stringRedisTemplate.delete(token);
        return Result.success();
    }

    //退出登录
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null) {
            // 从Redis中删除token
            stringRedisTemplate.delete(token);
        }
        // 清除ThreadLocal中的数据
        ThreadLocalUtil.remove();
        return Result.success();
    }

}
